package com.stylefeng.guns.modular.system.controller.server;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.common.annotion.BussinessLog;
import com.stylefeng.guns.common.constant.factory.PageFactory;
import com.stylefeng.guns.common.exception.BizExceptionEnum;
import com.stylefeng.guns.common.exception.BussinessException;
import com.stylefeng.guns.common.persistence.dao.CategoryMapper;
import com.stylefeng.guns.common.persistence.dao.DocumentsMapper;
import com.stylefeng.guns.common.persistence.dao.DocumentsPageMapper;
import com.stylefeng.guns.common.persistence.model.Category;
import com.stylefeng.guns.common.persistence.model.Documents;
import com.stylefeng.guns.common.persistence.model.DocumentsPage;
import com.stylefeng.guns.config.properties.GunsProperties;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.constants.Constant;
import com.stylefeng.guns.modular.system.dao.DocumentsDao;
import com.stylefeng.guns.modular.system.service.IDocumentsService;
import com.stylefeng.guns.modular.system.warpper.DocumentsWarpper;
import com.stylefeng.guns.modular.utils.QiniuUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author lmshe
 * @create 2017-11-16 14:44
 * @desc
 */
@Controller
@RequestMapping("/documents")
public class DocumentsController extends BaseController {
    private static String PREFIX = "/system/documents/";

    @Resource
    private DocumentsDao documentsDao;

    @Resource
    private DocumentsMapper documentsMapper;

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private DocumentsPageMapper documentsPageMapper;

    @Resource
    private GunsProperties gunsProperties;

    @Resource
    private IDocumentsService documentsService;



    /**
     * 跳转到文档管理页面
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "documents.html";
    }


    /**
     * 跳转到添加文档
     */
    @RequestMapping("/documents_add")
    public String documentsAdd(Model model) {
        List<Category> categoryList = this.categoryMapper.selectList(new EntityWrapper<Category>().eq("parent_id", 0));
        model.addAttribute("categoryList", categoryList);
        return PREFIX + "documents_add.html";
    }

    /**
     * 跳转到修改文档
     */
    @RequestMapping("/documents_update/{documentsId}")
    public String documentsUpdate(@PathVariable Long documentsId, Model model) {

        Documents documents = this.documentsMapper.selectById(documentsId);
        documents.setDownloadUrl(gunsProperties.getQiniuImgDomain() + documents.getDownloadUrl());
        model.addAttribute("documents", documents);
        List<Category> categoryList = this.categoryMapper.selectList(new EntityWrapper<Category>().eq("parent_id", 0));
        model.addAttribute("categoryList", categoryList);
        List<Category> categoryChildList = this.categoryMapper.selectList(new EntityWrapper<Category>().eq("parent_id", documents.getCategoryId()));
        model.addAttribute("categoryChildList", categoryChildList);
        LogObjectHolder.me().set(documents);
        return PREFIX + "documents_edit.html";
    }

    /**
     * @author lmshe
     * @create 11:20 2017/11/8
     * @desc 查询文档列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object list(@RequestParam(required = false) Integer categoryId,
                       @RequestParam(required = false) Integer categoryPId,
                       @RequestParam(required = false) String format,
                       @RequestParam(required = false) Integer priceType,
                       @RequestParam(required = false) String tag,
                       @RequestParam(required = false) String documentName
                       ) {
        Page<Map<String, Object>> page = new PageFactory<Map<String, Object>>().defaultPage();
        List<Map<String, Object>> result = documentsDao.getDocumentsList(page, categoryPId, categoryId, format, priceType, tag,documentName, page.getOrderByField(), page.isAsc());
        page.setRecords((List<Map<String, Object>>) new DocumentsWarpper(result).warp());
        return super.packForBT(page);
    }

    /**
     * 文档上架
     */
    @RequestMapping(value = "/online")
    @ResponseBody
    @BussinessLog(value = "文档上架", key = "documentsIds")
    public Object online(@RequestParam String documentsIds) {
        String[] idArr = documentsIds.split(",");
        for(String id : idArr){
            Documents documents = this.documentsMapper.selectById(Integer.parseInt(id));
            documents.setIsOnline(1);
            documents.updateById();
        }
        return super.SUCCESS_TIP;
    }

    /**
     * 文档下架
     */
    @RequestMapping(value = "/cancel_online")
    @ResponseBody
    @BussinessLog(value = "文档上架", key = "documentsIds")
    public Object cancelOnline(@RequestParam String documentsIds) {
        String[] idArr = documentsIds.split(",");
        for(String id : idArr){
            Documents documents = this.documentsMapper.selectById(Integer.parseInt(id));
            documents.setIsOnline(0);
            documents.updateById();
        }
        return super.SUCCESS_TIP;
    }

    /**
     * 修改文档
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    @BussinessLog(value = "修改文档", key = "documentsName")
    public Object update(Documents documents) {
        if (ToolUtil.isOneEmpty(documents, documents.getCategoryId(), documents.getCategoryChildId(), documents.getDocumentName())) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        if(documents.getPriceType() == 0){
            documents.setNormalPrice(new BigDecimal(0));
            documents.setMemberPrice(new BigDecimal(0));
        }else if(documents.getPriceType() == 1){
            documents.setMemberPrice(new BigDecimal(0));
        }
        //更新文件名
        Documents oldDocuments =  this.documentsMapper.selectById(documents.getId());
        if(!oldDocuments.getDocumentName().equals(documents.getDocumentName())){
            String du = oldDocuments.getDownloadUrl();
            String duFormat = du.substring(du.lastIndexOf("."),du.length());
            String newDu = du.substring(0,du.lastIndexOf("-") + 1) + documents.getDocumentName() + duFormat;
            documents.setDownloadUrl(newDu);
            QiniuUtil.rename(du,newDu);
        }
        this.documentsMapper.updateById(documents);
        return super.SUCCESS_TIP;
    }

    /**
     * 上传文件（产生文档记录，返回文档id）
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, path = "/upload")
    @ResponseBody
    public Map<String,Object> uploadFile(@RequestPart("file") MultipartFile file) {
        String name = file.getOriginalFilename();
        String fileName = "file-" + UUID.randomUUID().toString() + "-" + name;
        //上传文件到七牛
        int statusCode;
        try {
            statusCode = QiniuUtil.uploadByte(file.getBytes(), fileName);
        } catch (IOException e) {
            throw new BussinessException(BizExceptionEnum.UPLOAD_ERROR);
        }
        if (statusCode != 200) {
            throw new BussinessException(BizExceptionEnum.UPLOAD_ERROR);
        }
        String documentName = name.substring(0,name.lastIndexOf("."));
        //保存文档
        Documents documents = new Documents();
        documents.setDownloadUrl(fileName);
        documents.setFormat(getFormat(name));
        documents.setRealFormat(name.substring(name.lastIndexOf(".")));
        documents.setDocumentName(documentName);
        documents.setCreatetime(new Date());
        documentsMapper.insert(documents);
        //获取文件类型
        try {
            if (name.endsWith(Constant.DOC)) {
                /**
                 * doc文档处理
                 */
                documentsService.docToHtml(file.getInputStream(),documents.getId());
            } else if (name.endsWith(Constant.DOCX)) {
                /**
                 * docx文档处理
                 */
            } else if (name.endsWith(Constant.XLS)) {
                /**
                 * xls表格处理
                 */
                documentsService.xlsToHtml(file.getInputStream(),documents.getId());

            } else if (name.endsWith(Constant.XLSX)) {
                /**
                 * xlsx表格处理
                 */
                documentsService.xlsToHtml(file.getInputStream(),documents.getId());
            } else if (name.endsWith(Constant.PPT)) {
                /**
                 * ppt处理
                 */
                documentsService.pptToHtml(file.getInputStream(),documents.getId());
            } else if (name.endsWith(Constant.PPTX)) {
                /**
                 * pptx处理
                 */
                documentsService.pptxToHtml(file.getInputStream(),documents.getId());
            } else if (name.endsWith(Constant.PDF)) {
                /**
                 * pdf处理
                 */
                documentsService.pdfToHtml(fileName,documents.getId());
            } else {
                throw new BussinessException(BizExceptionEnum.TYPE_ERROR);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String,Object> result = new HashMap<>();
        result.put("id",documents.getId());
        result.put("documentName",documentName);
        LogObjectHolder.me().set(documents);
        return result;
    }

    /**
     * @author lmshe
     * @create 10:25 2017/11/23
     * @desc 获取文档类型
     */
    private static String getFormat(String name) throws BussinessException{
        String format;
        if (name.endsWith(Constant.DOC) || name.endsWith(Constant.DOCX)) {
            format = Constant.WORD;
        }else if (name.endsWith(Constant.XLS) || name.endsWith(Constant.XLSX)) {
            format = Constant.EXCEL;
        } else if (name.endsWith(Constant.PPT) || name.endsWith(Constant.PPTX)) {
            format = Constant.PPT_TYPE;
        } else if (name.endsWith(Constant.PDF)) {
            format = Constant.PDF_TYPE;
        } else {
            throw new BussinessException(BizExceptionEnum.TYPE_ERROR);
        }
        return format;
    }

    /**
     * 预览
     */
    @RequestMapping("/preview/{documentsId}")
    public String preview(@PathVariable Long documentsId, Model model) {
        Documents documents = documentsMapper.selectById(documentsId);
        String realFormat = documents.getRealFormat();
        String html = null;
        if(Constant.DOC.equals(realFormat)){
            html = documentsService.getDocHtml(documentsId);
        }else if(Constant.XLS.equals(realFormat) || Constant.XLSX.equals(realFormat)){
            html = documentsService.getExcelHtml(documentsId);
        }else if(Constant.PPT.equals(realFormat) || Constant.PPTX.equals(realFormat)){
            html = documentsService.getPPTHtml(documentsId);
        }else if(Constant.PDF.equals(realFormat)){
            html = documentsService.getPdfHtml(documentsId);
        }
        if(StringUtils.isBlank(html)){
            html = "预览出错！";
        }
        model.addAttribute("html", html);
        return PREFIX + "preview.html";
    }
}
